import { nextTick } from 'vue'
import _ from 'lodash'

    // 处理百分位展示
    const generatingThousandthPer = (num: number) => {
      return _.multiply(num, 100) + '%'
    }
let current:any=null

// 千分位
export default {
  mounted(el: { querySelector: (arg0: string) => any; }, binding: { modifiers: {}; value: { [x: string]: any; }; }, vnode: any) {
    const key = Object.keys(binding.modifiers)[0]
    if (!binding.value[key]) {
      binding.value[key] = '0'
    }

    // 赋值
    const assignment = (event:any, value:any, value2?:any) => {
      binding.value[key] = value
      nextTick(() => event.target.value = generatingThousandthPer(value2 || value))
    }
    // 处理最后一位非法字符
    const handlerIllegalStr = (str: string) => {
      while (!(/^[0-9]+.?[0-9]*/.test(str.charAt(str.length - 1)))) {
        str = str.substr(0, str.length - 1)
      }
      return str
    }

    const input = el.querySelector('input')
    input.style.textAlign="right"

    if (input) {
      input.setAttribute('data-rate', binding.value[key])
      nextTick(() => input.value = generatingThousandthPer(binding.value[key]))

      input.addEventListener('blur', (event: { target: { value: string; }; }) => {
        current=null
        const val = event.target.value
        // 是否是数字
        if (!val || isNaN(val as any) || Number(val) > 1 || Number(val) < 0) {
          /**
           * 如果不是数字 重置为原数据
           */
          const value = input.getAttribute('data-rate')
          binding.value[key] = value.replace(/%/g, '')
          nextTick(() => event.target.value = generatingThousandthPer(value))
          return false
        }
        input.setAttribute('data-rate', val)
        assignment(event, handlerIllegalStr(val.replace(/%/g, '')))
      })

      input.addEventListener('focus', (event: { target: { value: any; }; }) => {
        current=input
        const value = input.getAttribute('data-rate')
        const inp = event.target.value = value.replace(/%/g, '')
      })
    }
  },
    // 指令绑定元素因为数据修改触发修改后
    updated(
      el: { querySelector: (arg0: string) => any },
      binding: { modifiers: {}; value: { [x: string]: any } },
      vnode: any
    ) {
  
      const key = Object.keys(binding.modifiers)[0]
      const input = el.querySelector('input')
      if (current ==input) {
         return false
      }
      input.setAttribute('data-rate', binding.value[key])
      nextTick(
        () => (input.value = generatingThousandthPer(binding.value[key] ))
      )
    },
}

